package com.apexedu.biz.timer;

import com.apexedu.biz.entity.TAccessAppReg;
import com.apexedu.biz.entity.TSysUserInfo;
import com.apexedu.biz.entity.TTimer;
import com.apexedu.biz.entity.TTimerLog;
import com.apexedu.framework.dao.BaseDao;
import com.apexedu.framework.util.ConfigUtil;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.portal.util.DBMUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.util.*;

/**
 * 获取待办发送短信
 * Created by ly on 2015/5/22.
 */
public class WorkflowTimerTask extends TimerTask {
    protected Log log = LogFactory.getLog(this.getClass());//日志记录

    @Override
    public void run() {
        if (DBUtil.count("select count(*) from T_SCHEDULE where to_char(day,'yyyyMMdd')=to_char(sysdate,'yyyyMMdd')") == 0) {
            TTimerLog timerLog = new TTimerLog();
            StringBuffer sb = new StringBuffer("");
            String state = "1"; //定时器执行状态
            try {
                List<TSysUserInfo> list = DBUtil.queryAllBeanList("select a.userloginid as userid,t.phone" +
                        " from t_sys_user_info t inner join t_sys_user a on a.userid=t.userid where phone is not null and yhlx=1", TSysUserInfo.class);
                List<TAccessAppReg> listApp = DBUtil.queryAllBeanList("select * from t_access_app_reg where xtlx=1 and state=1", TAccessAppReg.class);
                Map<String, String> map = new HashMap<String, String>();
                for (TAccessAppReg appReg : listApp) {
                    try {
                        List<TSysUserInfo> listCount = new DBMUtil(appReg.getDb()).queryAllBeanList("select count(*) as yhlx,tt.userid as userid " +
                                " from (select cur.entry_id as id, t.userid from  os_currentstep cur" +
                                " inner join tuser t on instr(','||cur.owner||',',','||t.id||',')>0 ) tt group by tt.userid", TSysUserInfo.class);
                        if (!listCount.isEmpty()) {
                            for (TSysUserInfo info : listCount) {
                                String msg = map.get(info.getUserid());
                                if (msg == null) {
                                    msg = "您有" + info.getYhlx() + "个待处理文件，其中【" + appReg.getAppname() + "】:" + info.getYhlx() + "个；";
                                } else {
                                    int count = Integer.parseInt(msg.substring(msg.indexOf("有") + 1, msg.indexOf("个")));
                                    msg = "您有" + (count + info.getYhlx()) + msg.substring(msg.indexOf("个"))
                                            + "【" + appReg.getAppname() + "】:" + info.getYhlx() + "个；";
                                }
                                map.put(info.getUserid(), msg);
                            }
                        }
                    } catch (Exception e) {
                        sb.append(e.getMessage().substring(0, 1000));
                        log.error("WorkflowTimeTask error : " + e);
                        state = "0"; //定时器执行状态
                        continue;
                    }
                }
                DBMUtil dbmUtil = new DBMUtil("dxpt");
                for (TSysUserInfo info : list) {
                    String msg = map.get(info.getUserid());
                    if (msg != null) {
                        try {
                            log.debug(info.getPhone() + "====" + msg);
                            dbmUtil.executeSQL("insert into SMS_OUTBOX(DESTADDR,MESSAGECONTENT,REQDELIVERYREPORT,MSGFMT,SENDMETHOD,REQUESTTIME,APPLICATIONID)" +
                                            "values (?,?,1,0,2,now(),'P000000000000070')",
                                    info.getPhone(), msg);
                        } catch (Exception e) {
                            sb.append(e.getMessage().substring(0, 1000));
                            log.error("WorkflowTimeTask error : " + e);
                            state = "0"; //定时器执行状态
                            continue;
                        }
                    }
                }
            } catch (Exception eee) {
                sb.append(eee.getMessage().substring(0, 1000));
                log.error("WorkflowTimeTask error : " + eee);
                timerLog.setState("0");
                state = "0"; //定时器执行状态
            }
            Calendar cal = Calendar.getInstance();
            timerLog.setExecutesecond((cal.getTimeInMillis() - timerLog.getLasttime().getTime()) / 1000);
            timerLog.setState(state);
            timerLog.setErrorlog(sb.toString());
            String id = ConfigUtil.getString("timer.workflow.id");
            timerLog.setTid(id);
            WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
            BaseDao baseDao = (BaseDao) wac.getBean("baseDao");
            DBUtil.executeSQL("update t_timer_log set state='-1' where tid = ?", id);

            TTimer t = baseDao.findById(TTimer.class, id);
            int ms = t.getInterval().intValue();
            if ("m".equals(t.getIntervaltype())) {
                ms *= 60;
            } else if ("h".equals(t.getIntervaltype())) {
                ms *= 60 * 60;
            } else if ("d".equals(t.getIntervaltype())) {
                ms *= 60 * 60 * 24;
            }
            cal.add(Calendar.SECOND, ms);
            timerLog.setNexttime(cal.getTime());
            baseDao.save(timerLog);
        }
    }
}
